<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.userName" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="名称" prop="userName"></el-table-column>
        <el-table-column label="电话" prop="userPhonenum"></el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.userId)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.userId)"></el-button>
            <!-- 分配角色按钮 -->
            <!--              <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">-->
            <!--                <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>-->
            <!--              </el-tooltip>-->
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pageNum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
    <!--    添加用户的对话框-->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed">
      <!--      内容主题区域-->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
        <el-form-item label="手机号" prop="userPhonenum">
          <el-input v-model="addForm.userPhonenum"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="userPassword">
          <el-input v-model="addForm.userPassword"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="addForm.confirmPassword"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="addForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="userAge">
          <el-input v-model="addForm.userAge"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="userGender">
          <el-input v-model="addForm.userGender"></el-input>
        </el-form-item>
      </el-form>

      <!--      底部区域-->
      <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
    </el-dialog>
    <!--    修改用户信息的对话框-->
    <el-dialog
      title="编辑用户信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed">
      <!--     内容主题 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="手机号" prop="userPhonenum">
          <el-input v-model="editForm.userPhonenum"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="userPassword">
          <el-input v-model="editForm.userPassword"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="editForm.confirmPassword"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="editForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="userAge">
          <el-input v-model="editForm.userAge"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="userGender">
          <el-input v-model="editForm.userGender"></el-input>
        </el-form-item>
      </el-form>
      <!--      底部信息-->
      <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 再次输入密码的校验规则
    var confirmPwdRule = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.addForm.userPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    // 再次输入密码的校验规则
    var updateConfirmPwdRule = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.editForm.userPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    // 验证手机号码的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[34578]\d{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      // 返回一个错误提示
      cb(new Error('请输入合法的手机号码'))
    }
    var isNum = (rule, value, callback) => {
      const age = /^[0-9]*$/
      if (!age.test(value)) {
        callback(new Error('年龄只能为数字'))
      } else {
        callback()
      }
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        userName: '',
        pageNum: 1, // 当前的页数
        pageSize: 5 // 当前每页显示多少条数据
      },
      userlist: [],
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 控制编辑用户对话框的显示与隐藏
      editDialogVisible: false,
      //  添加用户的表单数据
      addForm: {
        userName: '',
        userPassword: '',
        confirmPassword: '',
        userPhonenum: '',
        userAge: '',
        userGender: ''
      },
      // 添加表单的验证规则对象
      addFormRules: {
        userName: [
          { required: false, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符之间', trigger: 'blur' }
        ],
        // 验证密码
        userPassword: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符之间', trigger: 'blur' }
        ],
        // 验证确认密码
        confirmPassword: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          { validator: confirmPwdRule, trigger: 'blur' }
        ],
        userPhonenum: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        userAge: [
          { required: false, message: '请输入年龄', trigger: 'blur' },
          { validator: isNum, trigger: 'blur' }
        ],
        userGender: [
          { required: false, message: '请输入性别', trigger: 'blur' }
        ]
      },
      editForm: {},
      //  修改表单的验证规则对象
      editFormRules: {
        userName: [
          { required: false, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符之间', trigger: 'blur' }
        ],
        // 验证密码
        userPassword: [
          { required: false, message: '请输入登录密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符之间', trigger: 'blur' }
        ],
        // 验证确认密码
        confirmPassword: [
          { required: false, message: '请输入登录密码', trigger: 'blur' },
          { validator: updateConfirmPwdRule, trigger: 'blur' }
        ],
        userPhonenum: [
          { required: false, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        userAge: [
          { required: false, message: '请输入年龄', trigger: 'blur' },
          { validator: isNum, trigger: 'blur' }
        ],
        userGender: [
          { required: false, message: '请输入性别', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('getusers', {
        params: this.queryInfo
      })
      if (res.status !== 200) {
        return this.$message.error('获取权限列表失败！')
      }
      console.log(res)
      this.userlist = res.data.list
      this.total = res.data.total
    },
    // 监听 pagesize 改变的事件
    handleSizeChange (newSize) {
      // console.log(newSize)
      this.queryInfo.pageSize = newSize
      this.getUserList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange (newPage) {
      console.log(newPage)
      this.queryInfo.pageNum = newPage
      this.getUserList()
    },
    // 展示编辑用户的对话框
    async showEditDialog (userId) {
      console.log(userId)
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('getuserbyid', { params: { userId: userId } })
      if (res.status !== 200) {
        return this.$message.error('查询用户信息失败')
      }
      this.editForm = res.data
    },
    //  根据id删除对应的用户信息
    async removeUserById (userId) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      //  如果用户确认删除，则返回值为字符串 confirm
      //  如果用户取消了删除，则返回值为字符串cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消')
      }
      const { data: res } = await this.$http.get('deleteuserbyid', { params: { userId: userId } })
      if (res.status !== 200) {
        return this.$message.error('删除用户失败！')
      }
      this.$message.success('删除用户成功！')
      this.getUserList()
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    //  点击按钮，添加新用户
    addUser () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 可以发起添加用户的网络请求
        console.log(this.addForm)
        const { data: res } = await this.$http.post('adduser', this.addForm)
        if (res.status !== 200) {
          return this.$message.error(res.msg)
        }
        this.$message.success('添加用户成功！')
        //  隐藏添加用户的对话框
        this.addDialogVisible = false
        // 获取用户列表信息
        this.getUserList()
      })
    },
    //  监听修改用户信息的关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    //  修改用户信息并提交
    editUserInfo () {
      this.$refs.editFormRef.validate(async valid => {
        console.log(valid)
        if (!valid) return
        //  发起修改用户信息的数据请求
        const { data: res } = await this.$http.post('updateuser', this.editForm)
        if (res.status !== 200) {
          return this.$message.error('更新用户信息失败！')
        }
        //  关闭对话框
        this.editDialogVisible = false
        //  刷新数据列表
        this.getUserList()
        //  提示修改成功
        this.$message.success('更新用户信息成功!')
      })
    }
  }
}
</script>

<style scoped>

</style>
